package com.yuanduo_app.ui.map.control;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.google.gson.Gson;
import cn.ydxlm.maplib.MapManager;
import cn.ydxlm.maplib.api.LocationListener;
import cn.ydxlm.maplib.entity.Location;
import cn.ydxlm.maplib.widget.MapView;
import com.xujl.fastlib.http.ApiDisposableObserver;
import com.xujl.fastlib.http.BaseResponse;
import com.xujl.fastlib.utils.CollectionsUtils;
import com.xujl.fastlib.utils.NumberUtils;

import com.yuanduo_app.R;
import com.yuanduo_app.base.BaseRNActivity;
import com.yuanduo_app.bridge.RNBridgeModule;
import com.yuanduo_app.consts.PermissionGroup;
import com.yuanduo_app.consts.RNEvent;
import com.yuanduo_app.entity.NearbyOilEntity;
import com.yuanduo_app.entity.NearbyOilLevelEntity;
import com.yuanduo_app.manager.RNModuleManager;
import com.yuanduo_app.ui.map.model.NearbyOilActivityModel;
import com.yuanduo_app.ui.map.view.NearbyOilActivityView;
import com.yuanduo_app.utils.MapUtils;
import com.yuanduo_app.window.CommonInfoWindow;
import com.yuanduo_app.window.NearbyOilBottomWindow;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;


/**
 * <pre>
 *     author : xujl
 *     e-mail : 597355068@qq.com
 *     time   : 2019/08/20
 *     desc   : 附近加油站
 *     version: 1.0
 * </pre>
 */
public class NearbyOilActivityControl extends BaseRNActivity<NearbyOilActivityModel, NearbyOilActivityView> implements LocationListener,
        NearbyOilBottomWindow.Callback, MapView.OnMarkerClickListener, MapView.OnMapClickListener {
    private static final String TAG = "NearbyOilActivityControl";

    @Override
    public void init (Bundle savedInstanceState) {
        MapManager.getInstance().addLocationListener(this);
        mModel.saveBundle(getIntent().getExtras());
        mView.onCreate(savedInstanceState);
        requestRuntimePermissions(PermissionGroup.LOCATION);
    }

//    public void requestPermissions () {
//        LogS.d(TAG, "requestPermissions");
//        MapManager.getInstance().startLocation();
//        mModel.getAllOilType(createObserver());
//    }

    @Override
    protected void onSaveInstanceState (@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        mView.onSaveInstanceState(outState);
    }

    public void showPermissionWindow () {
        final CommonInfoWindow infoWindow = new CommonInfoWindow(this,
                CommonInfoWindow.createBuilder()
                        .setInfo("本页面需要使用定位功能。\n是否继续使用？")
                        .setRightStr("继续使用")
                        .setLeftStr("退出")
        );
        infoWindow.setCallback(code -> {
            if (code == CommonInfoWindow.RIGHT_BTN) {
            } else {
                finish();
            }
        });
        infoWindow.showPopupWindow();
    }


    @Override
    protected void permissionsComplete (String[] permissions) {
        super.permissionsComplete(permissions);
        if (!MapUtils.isGpsOpen(this)) {
            return;
        }
        MapManager.getInstance().startLocation();
        mModel.getAllOilType(createObserver());
    }

    @Override
    public void onReceiveLocation (Location location) {
        mView.setCenterPoint(location);
        mModel.mLocation = location;
        mModel.queryStationInfo(new ApiDisposableObserver<List<NearbyOilEntity>>(this) {
            @Override
            public void onResult (BaseResponse<List<NearbyOilEntity>> response, List<NearbyOilEntity> data) {
                mModel.setNearbyOilEntity(data);
                mView.showNearStation(mModel.getMarkerList(data));
            }
        });
    }


    @Override
    public void onClick (View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.iv_get_location:
                MapManager.getInstance().startLocation();
                break;
            case R.id.ll_choose:
                //选择标号
                mView.showChooseOilLevel(mModel.mOilLevelEntities);
                break;
            case R.id.fl_nav:
                final double[] end = MapUtils.bdToGaoDe(NumberUtils.doubleOf(mModel.getNearbyOilEntity().getLatitude())
                        , NumberUtils.doubleOf(mModel.getNearbyOilEntity().getLongitude()));
                MapUtils.openGaoDeNavi(0,
                        0, "", end[0], end[1]
                        , mModel.getNearbyOilEntity().getAddress());
                break;
            case R.id.iv_list_back:
                finish();
                break;
            case R.id.iv_back:
                finish();
                break;
            default:

                break;

        }
    }

    private ApiDisposableObserver<List<NearbyOilLevelEntity>> createObserver () {
        return new ApiDisposableObserver<List<NearbyOilLevelEntity>>(this) {
            @Override
            public void onResult (BaseResponse<List<NearbyOilLevelEntity>> response, List<NearbyOilLevelEntity> data) {
                CollectionsUtils.addAll(mModel.mOilLevelEntities, data);
            }
        };
    }

    @Override
    public void onBackPressedSupport () {
        RNBridgeModule module = RNModuleManager.getInstance().getModule(RNBridgeModule.class);
        if (mModel != null && module != null) {
            Map<String, String> map = new HashMap<>(1);
            map.put("businessNo", mModel.currentOilLevel.get());
            module.sendEvent(RNEvent.OIL_BACK, new Gson().toJson(map));
        }
        super.onBackPressedSupport();
    }

    @Override
    protected void onDestroy () {
        MapManager.getInstance().removeLocationListener(this);
        super.onDestroy();
    }

    @Override
    public void onItemClick (NearbyOilLevelEntity entity) {
        mModel.currentOilLevel.set(entity.getBusinessNo());
        mModel.queryStationInfo(new ApiDisposableObserver<List<NearbyOilEntity>>(this) {
            @Override
            public void onResult (BaseResponse<List<NearbyOilEntity>> response, List<NearbyOilEntity> data) {
                mModel.setNearbyOilEntity(data);
                mView.showNearStation(mModel.getMarkerList(data));
            }
        });
    }

    @Override
    public void onMarkerClick (int position) {
        mModel.setNearbyOilEntity(mModel.mOilEntities.get(position));
    }

    @Override
    public void OnMapClick (double lat, double lon) {
        final Location location = new Location();
        location.setLatitude(lat);
        location.setLongitude(lon);
        mModel.mLocation = location;
        mModel.queryStationInfo(new ApiDisposableObserver<List<NearbyOilEntity>>(this) {
            @Override
            public void onResult (BaseResponse<List<NearbyOilEntity>> response, List<NearbyOilEntity> data) {
                mModel.setNearbyOilEntity(data);
                mView.showNearStation(mModel.getMarkerList(data));
            }
        });
        mView.setCenterPoint(location);
    }

    @Override
    public void onActivityResult (int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case MapUtils.PRIVATE_CODE:
                requestRuntimePermissions(PermissionGroup.LOCATION);
                break;

        }
    }
}
